<?php

class TempModel extends CActiveRecord
{

	private static $_tableN = "";
	private $_md = null;

	public function __construct($scenario = 'insert', $table = "")
	{
		if (!empty($table))
		{
			self::$_tableN = $table;
		}
		parent::__construct($scenario);
	}

	public function init()
	{
		$this->_md = new CActiveRecordMetaData($this);
		parent::init();
	}

	public static function model($className = __CLASS__)
	{
		return parent::model($className);
	}

	public function tableName()
	{
//		/die($this->_tableN);
		return self::$_tableN;
	}

	function setTableName($tableName)
	{
		self::$_table = $tableName;
		return $this;
	}

	public function refreshMetaData()
	{
		$this->_md = new CActiveRecordMetaData($this);
		return $this;
	}

}

class ModuleFullCode extends CCodeModel
{

	public $moduleID;
	public $tables = array();
	public $tablePrefix;
	public $tableName;
	public $modelClass;
	public $modelPath = 'application.models';
	public $baseClass = 'CActiveRecord';
	//public $ignoreSufix = "_langs _ru _uk _versions";
	public $ignoreSufix = "";
	public $controllerClass = "";
	public $baseControllerClass = "AdminController";
	private $_table;

	/**
	 * @var array list of candidate relation code. The array are indexed by AR class names and relation names.
	 * Each element represents the code of the one relation in one AR class.
	 */
	protected $relations;

	public function requiredTemplates()
	{
		return array(
			'model.php',
		);
	}

	public function init()
	{
		if (Yii::app()->db === null)
			throw new CHttpException(500, 'An active "db" connection is required to run this generator.');
		$this->tablePrefix = Yii::app()->db->tablePrefix;
		parent::init();
	}

	public function rules()
	{
		return array_merge(parent::rules(), array(
					array('moduleID', 'filter', 'filter' => 'trim'),
					array('moduleID', 'required'),
					array('moduleID', 'match', 'pattern' => '/^\w+$/', 'message' => '{attribute} should only contain word characters.'),
						), array(
					array('tablePrefix, baseClass, tableName, modelClass, modelPath', 'filter', 'filter' => 'trim'),
					array('tableName, modelPath, baseClass', 'required'),
					array('tablePrefix, tableName, modelPath', 'match', 'pattern' => '/^(\w+[\w\.]*|\*?|\w+\.\*|[\w\s]*)$/', 'message' => '{attribute} should only contain word characters, dots, and an optional ending asterisk.'),
					array('tableName', 'validateTableName', 'skipOnError' => true),
					array('tablePrefix, baseClass', 'match', 'pattern' => '/^[a-zA-Z_][\w\s]*$/', 'message' => '{attribute} should only contain word characters.'),
					//array('modelPath', 'validateModelPath', 'skipOnError'=>true),
					array('baseClass', 'validateReservedWord', 'skipOnError' => true),
					array('baseClass', 'validateBaseClass', 'skipOnError' => true),
					array('tablePrefix, modelPath, baseClass', 'sticky'),
				));
	}

	public function attributeLabels()
	{
		return array_merge(parent::attributeLabels(), array(
					'moduleID' => 'Module ID',
						), array(
					'tablePrefix' => 'Table Prefix',
					'tableName' => 'Table Name',
					'modelPath' => 'Model Path',
					'modelClass' => 'Model Class',
					'baseClass' => 'Base Class',
				));
	}

	public function successMessage()
	{
		if (Yii::app()->hasModule($this->moduleID))
			return 'The module has been generated successfully. You may ' . CHtml::link('try it now', Yii::app()->createUrl($this->moduleID), array('target' => '_blank')) . '.';

		$output = <<<EOD
<p>The module has been generated successfully.</p>
<p>To access the module, you need to modify the application configuration as follows:</p>
EOD;
		$code = <<<EOD
<?php
return array(
    'modules'=>array(
        '{$this->moduleID}',
    ),
    ......
);
EOD;

		return $output . highlight_string($code, true);
	}

	private function checkSufix($tableName)
	{
		foreach ($this->ignoreSufix as $suf)
		{
			$suf = trim($suf);
			if (!empty($suf) && strpos($tableName, $suf) !== false/* &&strlen($tableName)-strpos($tableName,$suf)==strlen($suf) */)
			{
				return true;
			}
		}
		return false;
	}

	public function prepare()
	{
		$this->ignoreSufix = explode(' ', $this->ignoreSufix);
		$this->files = array();
		$templatePath = $this->templatePath;
		$modulePath = $this->modulePath;
		$moduleTemplateFile = $templatePath . DIRECTORY_SEPARATOR . 'module.php';
		$controllerTemplateFile = $templatePath . DIRECTORY_SEPARATOR . 'controller.php';

		$this->modelPath = $this->modulePath . DIRECTORY_SEPARATOR . 'models';

		//$templatePath=$this->templatePath;

		if (($pos = strrpos($this->tableName, '.')) !== false)
		{
			$schema = substr($this->tableName, 0, $pos);
			$tableName = substr($this->tableName, $pos + 1);
		}
		else
		{
			$schema = '';
			$tableName = $this->tableName;
		}
		if ($tableName[strlen($tableName) - 1] === '*')
		{
			$this->tables = Yii::app()->db->schema->getTables($schema);
			if ($this->tablePrefix != '')
			{
				foreach ($this->tables as $i => $table)
				{
					if (strpos($table->name, $this->tablePrefix) !== 0)
					{
						unset($this->tables[$i]);
					}
					else if ($this->checkSufix($table->name))
					{
						unset($this->tables[$i]);
					}
				}
			}
		}
		else
			$this->tables = array($this->getTableSchema($this->tableName));
		if (($pos = strrpos($this->tableName, ' ')) !== false)
		{
			$t = split(' ', trim($this->tableName));
			$this->tables = array();
			foreach ($t as $table)
			{
				$this->tables[] = $this->getTableSchema($table);
			}
		}
		else
		{
			$schema = '';
			$tableName = $this->tableName;
		}
		$this->relations = $this->generateRelations();

		$this->files[] = new CCodeFile(
						$modulePath . DIRECTORY_SEPARATOR . $this->moduleClass . '.php',
						$this->render($moduleTemplateFile)
		);

		if (count($this->tables) == 1)
		{
			$params_FH = array(
				'exclude' => array('.svn', 'crud', 'AdminDefaultController.php'),
			);
		}
		else
		{
			$params_FH = array(
				'exclude' => array('.svn', 'crud'),
			);
		}

		$files = CFileHelper::findFiles($templatePath, $params_FH);

		foreach ($files as $file)
		{
			if ($file !== $controllerTemplateFile && $file !== $moduleTemplateFile && $file !== $templatePath . DIRECTORY_SEPARATOR . 'model.php')
			{
				if (CFileHelper::getExtension($file) === 'php')
					$content = $this->render($file);
				else if (basename($file) === '.yii')
				{  // an empty directory
					$file = dirname($file);
					$content = null;
				}
				else
					$content = file_get_contents($file);
				$this->files[] = new CCodeFile(
								$modulePath . substr($file, strlen($templatePath)),
								$content
				);
			}
		}

		foreach ($this->tables as $table)
		{
			$tableName = $this->removePrefix($table->name);
			$className = $this->generateClassName($table->name);
			$params = array(
				'tableName' => $schema === '' ? $tableName : $schema . '.' . $tableName,
				'modelClass' => $className,
				'columns' => $table->columns,
				'labels' => $this->generateLabels($table),
				'rules' => $this->generateRules($table),
				'relations' => isset($this->relations[$className]) ? $this->relations[$className] : array(),
			);
			$this->files[] = new CCodeFile(
							$this->modelPath . DIRECTORY_SEPARATOR . $className . '.php',
							$this->render($templatePath . DIRECTORY_SEPARATOR . 'model.php', $params)
			);
			//print "<pre>";
			if (count($this->tables) == 1)
			{
				$this->controllerClass = 'AdminDefaultController';
			}
			else
			{
				$this->controllerClass = 'Admin' . $className . 'Controller';
			}
			$this->modelClass = $className;
			//print_r($table);
			$m = new TempModel('insert', $table->name);
			//print_r($m);die();
			//$m->setTableName($table);
			//$m->refreshMetaData();
			$this->_table = $m->tableSchema;
			$this->files[] = new CCodeFile(
							$modulePath . DIRECTORY_SEPARATOR . 'controllers' . DIRECTORY_SEPARATOR . $this->controllerClass . '.php',
							$this->render($controllerTemplateFile)
			);

			$files = scandir($templatePath . DIRECTORY_SEPARATOR . "crud");
			foreach ($files as $file)
			{
				if (is_file($templatePath . DIRECTORY_SEPARATOR . "crud" . DIRECTORY_SEPARATOR . $file) && CFileHelper::getExtension($file) === 'php')
				{
					$this->files[] = new CCodeFile(
									$modulePath . DIRECTORY_SEPARATOR . 'views' . DIRECTORY_SEPARATOR . 'admin' . (count($this->tables) == 1 ? 'Default' : $className) . DIRECTORY_SEPARATOR . $file,
									$this->render($templatePath . DIRECTORY_SEPARATOR . "crud" . DIRECTORY_SEPARATOR . $file)
					);
				}
			}
		}
	}

	public function getModuleClass()
	{
		return ucfirst($this->moduleID) . 'Module';
	}

	public function getModulePath()
	{
		return Yii::app()->modulePath . DIRECTORY_SEPARATOR . $this->moduleID;
	}

	public function validateTableName($attribute, $params)
	{
		if ($this->tableName != '' && $this->tableName[strlen($this->tableName) - 1] === '*')
			$this->modelClass = '';
		else
		{
			if (($pos = strrpos($this->tableName, ' ')) === false && $this->getTableSchema($this->tableName) === null)
				$this->addError('tableName', "Table '{$this->tableName}' does not exist.");
			/* if($this->modelClass==='')
			  $this->addError('modelClass','Model Class cannot be blank.'); */
		}
	}

	public function validateModelPath($attribute, $params)
	{
		if (Yii::getPathOfAlias($this->modelPath) === false)
			$this->addError('modelPath', 'Model Path must be a valid path alias.');
	}

	public function validateBaseClass($attribute, $params)
	{
		$class = @Yii::import($this->baseClass, true);
		if (!is_string($class) || !$this->classExists($class))
			$this->addError('baseClass', "Class '{$this->baseClass}' does not exist or has syntax error.");
		else if ($class !== 'CActiveRecord' && !is_subclass_of($class, 'CActiveRecord'))
			$this->addError('baseClass', "'{$this->model}' must extend from CActiveRecord.");
	}

	public function getModelTableSchema()
	{
		return $this->_table;
	}

	public function getTableSchema($tableName = null)
	{
		if (!$tableName)
			$tableName = $this->_table;
		if (!is_string($tableName))
			return $tableName;
		//echo "<pre>",print_r($tableName,true),'</pre><br>';
		//echo "<pre>",print_r(Yii::app()->db->getSchema()->getTables(),true),'</pre><br>';DIE;
		return Yii::app()->db->getSchema()->getTable(trim($tableName));
	}

	public function generateLabels($table)
	{
		$labels = array();
		foreach ($table->columns as $column)
		{
			$label = ucwords(trim(strtolower(str_replace(array('-', '_'), ' ', preg_replace('/(?<![A-Z])[A-Z]/', ' \0', $column->name)))));
			$label = preg_replace('/\s+/', ' ', $label);
			if (strcasecmp(substr($label, -3), ' id') === 0)
				$label = substr($label, 0, -3);
			if ($label === 'Id')
				$label = 'ID';
			$labels[$column->name] = $label;
		}
		return $labels;
	}

	public function generateRules($table)
	{
		$rules = array();
		$required = array();
		$integers = array();
		$numerical = array();
		$length = array();
		$safe = array();
		foreach ($table->columns as $column)
		{
			if ($column->isPrimaryKey && $table->sequenceName !== null)
				continue;
			$r = !$column->allowNull && $column->defaultValue === null;
			if ($r)
				$required[] = $column->name;
			if ($column->type === 'integer')
				$integers[] = $column->name;
			else if ($column->type === 'double')
				$numerical[] = $column->name;
			else if ($column->type === 'string' && $column->size > 0)
				$length[$column->size][] = $column->name;
			else if (!$column->isPrimaryKey && !$r)
				$safe[] = $column->name;
		}
		if ($required !== array())
			$rules[] = "array('" . implode(', ', $required) . "', 'required')";
		if ($integers !== array())
			$rules[] = "array('" . implode(', ', $integers) . "', 'numerical', 'integerOnly'=>true)";
		if ($numerical !== array())
			$rules[] = "array('" . implode(', ', $numerical) . "', 'numerical')";
		if ($length !== array())
		{
			foreach ($length as $len => $cols)
				$rules[] = "array('" . implode(', ', $cols) . "', 'length', 'max'=>$len)";
		}
		if ($safe !== array())
			$rules[] = "array('" . implode(', ', $safe) . "', 'safe')";

		return $rules;
	}

	public function getRelations($className)
	{
		return isset($this->relations[$className]) ? $this->relations[$className] : array();
	}

	protected function removePrefix($tableName, $addBrackets = true)
	{
		if ($addBrackets && Yii::app()->db->tablePrefix == '')
			return $tableName;
		$prefix = $this->tablePrefix != '' ? $this->tablePrefix : Yii::app()->db->tablePrefix;
		if ($prefix != '')
		{
			if ($addBrackets && Yii::app()->db->tablePrefix != '')
			{
				$prefix = Yii::app()->db->tablePrefix;
				$lb = '{{';
				$rb = '}}';
			}
			else
				$lb = $rb = '';
			if (($pos = strrpos($tableName, '.')) !== false)
			{
				$schema = substr($tableName, 0, $pos);
				$name = substr($tableName, $pos + 1);
				if (strpos($name, $prefix) === 0)
					return $schema . '.' . $lb . substr($name, strlen($prefix)) . $rb;
			}
			else if (strpos($tableName, $prefix) === 0)
				return $lb . substr($tableName, strlen($prefix)) . $rb;
		}
		return $tableName;
	}

	protected function generateRelations()
	{
		$relations = array();
		foreach (Yii::app()->db->schema->getTables() as $table)
		{
			if ($this->tablePrefix != '' && strpos($table->name, $this->tablePrefix) !== 0)
				continue;
			$tableName = $table->name;

			if ($this->isRelationTable($table))
			{
				$pks = $table->primaryKey;
				$fks = $table->foreignKeys;

				$table0 = $fks[$pks[0]][0];
				$table1 = $fks[$pks[1]][0];
				$className0 = $this->generateClassName($table0);
				$className1 = $this->generateClassName($table1);

				$unprefixedTableName = $this->removePrefix($tableName);

				$relationName = $this->generateRelationName($table0, $table1, true);
				$relations[$className0][$relationName] = "array(self::MANY_MANY, '$className1', '$unprefixedTableName($pks[0], $pks[1])')";

				$relationName = $this->generateRelationName($table1, $table0, true);
				$relations[$className1][$relationName] = "array(self::MANY_MANY, '$className0', '$unprefixedTableName($pks[1], $pks[0])')";
			}
			else
			{
				$className = $this->generateClassName($tableName);
				foreach ($table->foreignKeys as $fkName => $fkEntry)
				{
					// Put table and key name in variables for easier reading
					$refTable = $fkEntry[0]; // Table name that current fk references to
					$refKey = $fkEntry[1];   // Key in that table being referenced
					$refClassName = $this->generateClassName($refTable);

					// Add relation for this table
					$relationName = $this->generateRelationName($tableName, $fkName, false);
					$relations[$className][$relationName] = "array(self::BELONGS_TO, '$refClassName', '$fkName')";

					// Add relation for the referenced table
					$relationType = $table->primaryKey === $fkName ? 'HAS_ONE' : 'HAS_MANY';
					$relationName = $this->generateRelationName($refTable, $this->removePrefix($tableName, false), $relationType === 'HAS_MANY');
					$relations[$refClassName][$relationName] = "array(self::$relationType, '$className', '$fkName')";
				}
			}
		}
		return $relations;
	}

	/**
	 * Checks if the given table is a "many to many" pivot table.
	 * Their PK has 2 fields, and both of those fields are also FK to other separate tables.
	 * @param CDbTableSchema table to inspect
	 * @return boolean true if table matches description of helpter table.
	 */
	protected function isRelationTable($table)
	{
		$pk = $table->primaryKey;
		return (count($pk) === 2 // we want 2 columns
				&& isset($table->foreignKeys[$pk[0]]) // pk column 1 is also a foreign key
				&& isset($table->foreignKeys[$pk[1]]) // pk column 2 is also a foriegn key
				&& $table->foreignKeys[$pk[0]][0] !== $table->foreignKeys[$pk[1]][0]); // and the foreign keys point different tables
	}

	protected function generateClassName($tableName)
	{
		if ($this->tableName === $tableName || ($pos = strrpos($this->tableName, '.')) !== false && substr($this->tableName, $pos + 1) === $tableName)
			return $this->modelClass;

		$tableName = $this->removePrefix($tableName, false);
		$className = '';
		foreach (explode('_', $tableName) as $name)
		{
			if ($name !== '')
				$className.=ucfirst($name);
		}
		return $className;
	}

	/**
	 * Generate a name for use as a relation name (inside relations() function in a model).
	 * @param string the name of the table to hold the relation
	 * @param string the foreign key name
	 * @param boolean whether the relation would contain multiple objects
	 * @return string the relation name
	 */
	protected function generateRelationName($tableName, $fkName, $multiple)
	{
		if (strcasecmp(substr($fkName, -2), 'id') === 0 && strcasecmp($fkName, 'id'))
			$relationName = rtrim(substr($fkName, 0, -2), '_');
		else
			$relationName = $fkName;
		$relationName[0] = strtolower($relationName);

		$rawName = $relationName;
		if ($multiple)
			$relationName = $this->pluralize($relationName);

		$table = Yii::app()->db->schema->getTable($tableName);
		$i = 0;
		while (isset($table->columns[$relationName]))
			$relationName = $rawName . ($i++);

		$names = preg_split('/_+/', $relationName, -1, PREG_SPLIT_NO_EMPTY);
		if (empty($names))
			return $relationName;  // unlikely
		for ($name = $names[0], $i = 1; $i < count($names); ++$i)
			$name.=ucfirst($names[$i]);
		return $name;
	}

	public function generateInputLabel($modelClass, $column)
	{
		return "CHtml::activeLabelEx(\$model,'{$column->name}')";
	}

	public function generateInputField($modelClass, $column, $search = false)
	{
		if ($column->type === 'boolean' || $column->dbType === 'tinyint(1)')
			return "CHtml::activeCheckBox(\$model,'{$column->name}')";
		else if (stripos($column->dbType, 'text') !== false)
		//return "CHtml::activeTextArea(\$model,'{$column->name}',array('rows'=>6, 'cols'=>50))";
			if ($search)
			{
				return "\$form->textArea(\$model,'{$column->name}',array('rows'=>6, 'cols'=>50))";
			}
			else
			{
				return "\$this->widget('ext.widgets.ckeditor.CKEditor', array('model'=>\$model,'attribute'=>'{$column->name}','editorTemplate'=>'Optimal',)); ";
			}
		else
		{
			if (preg_match('/^(password|pass|passwd|passcode)$/i', $column->name))
				$inputField = 'activePasswordField';
			else
				$inputField = 'activeTextField';

			if ($column->type !== 'string' || $column->size === null)
				return "CHtml::{$inputField}(\$model,'{$column->name}')";
			else
			{
				if (($size = $maxLength = $column->size) > 60)
					$size = 60;
				return "CHtml::{$inputField}(\$model,'{$column->name}',array('size'=>$size,'maxlength'=>$maxLength))";
			}
		}
	}

	public function generateActiveLabel($modelClass, $column)
	{
		return "\$form->labelEx(\$model,'{$column->name}')";
	}

	public function generateActiveField($modelClass, $column, $search = false)
	{
		if ($column->type === 'boolean' || $column->dbType === 'tinyint(1)')
			return "\$form->checkBox(\$model,'{$column->name}')";
		else if (stripos($column->dbType, 'text') !== false)
			if ($search)
			{
				return "\$form->textArea(\$model,'{$column->name}',array('rows'=>6, 'cols'=>50))";
			}
			else
			{
				return "\$this->widget('ext.widgets.ckeditor.CKEditor', array('model'=>\$model,'attribute'=>'{$column->name}','editorTemplate'=>'Optimal',)); ";
			}
		else
		{
			if (preg_match('/^(password|pass|passwd|passcode)$/i', $column->name))
				$inputField = 'passwordField';
			else
				$inputField = 'textField';

			if ($column->type !== 'string' || $column->size === null)
				return "\$form->{$inputField}(\$model,'{$column->name}')";
			else
			{
				if (($size = $maxLength = $column->size) > 60)
					$size = 60;
				return "\$form->{$inputField}(\$model,'{$column->name}',array('size'=>$size,'maxlength'=>$maxLength))";
			}
		}
	}

	public function guessNameColumn($columns)
	{
		foreach ($columns as $column)
		{
			if (!strcasecmp($column->name, 'name'))
				return $column->name;
		}
		foreach ($columns as $column)
		{
			if (!strcasecmp($column->name, 'title'))
				return $column->name;
		}
		foreach ($columns as $column)
		{
			if ($column->isPrimaryKey)
				return $column->name;
		}
		return 'id';
	}

}